package test.my.com.myapplicationtest.SocketClient;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import test.my.com.myapplicationtest.R;
import test.my.com.myapplicationtest.utils.GsonUtil;
import test.my.com.myapplicationtest.utils.LogUtil;

/**
 * Author : Cooper
 * Time : 2017/10/30  15:41
 * Description : 远程绘制
 */

public class SocketRemoteDrawActivity extends Activity {

    @Bind(R.id.remote_draw_view)
    RemoteDrawView mRemoteDrawView;
    @Bind(R.id.bt_send)
    Button mBtSend;
    @Bind(R.id.bt_receive)
    Button mBtReceive;

    private Socket mSocket;
    private BufferedReader mBufferedReader;
    private BufferedWriter mBufferedWriter;
    private String ip = "192.168.10.137";
    private int port = 2000;

    private List<ActionPosition> mActionPositionList = new ArrayList<>();

    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
    private boolean mIsRemoteStart; // 是否远程绘画开始
    private SocketHandler mSocketHandler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aty_socket_remote_draw_layout);
        ButterKnife.bind(this);

        mRemoteDrawView.setActionPositionCallBack(new RemoteDrawView.ActionPositionCallBack() {
            @Override
            public void getActionPosition(ActionPosition actionPosition) {
                mActionPositionList.add(actionPosition);
            }
        });
        mSocketHandler = new SocketHandler();
        initSocket();

    }


    /**
     * 初始化socket
     */
    private void initSocket() {
        //新建一个线程，用于初始化socket和检测是否有接收到新的消息
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {

                try {
                    mSocket = new Socket(ip, port);
                    mBufferedReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream(), "utf-8"));
                    mBufferedWriter = new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "utf-8"));
                    mIsRemoteStart = true;
                    while (mIsRemoteStart) {
                        if (mBufferedReader.ready()) {
                            /*读取一行字符串，读取的内容来自于客户机
                            reader.readLine()方法是一个阻塞方法，
                            从调用这个方法开始，该线程会一直处于阻塞状态，
                            直到接收到新的消息，代码才会往下走*/
                            String data = mBufferedReader.readLine();
                            //handler发送消息，在handleMessage()方法中接收
                            LogUtil.e("ah  receive  data  ========>>   "+data);
                            Message msg = mSocketHandler.obtainMessage();
                            msg.obj = data;
                            msg.arg1 = 0;
                            mSocketHandler.sendMessage(msg);
                        }
                    }
                    mBufferedWriter.close();
                    mBufferedReader.close();
                    mSocket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

    /**
     * 发送
     */
    private void send() {

        new Thread(new SendRunnable()).start();
    }

    @OnClick({R.id.bt_send, R.id.bt_receive})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_send:
                send();
                break;
            case R.id.bt_receive:
//                receiveAction();
                break;
        }
    }

    class SendRunnable implements Runnable {

        @Override
        public void run() {
            while (mIsRemoteStart) {
                if (mActionPositionList.size() > 0) {
                    for (ActionPosition actionPosition : mActionPositionList) {
                        try {
                            JSONObject json = new JSONObject();
                            json.put("to", actionPosition.to);
                            json.put("from", actionPosition.from);
                            json.put("positionX", actionPosition.positionX);
                            json.put("positionY", actionPosition.positionY);
                            json.put("actionType", actionPosition.actionType);
                            mBufferedWriter.write(json.toString() + "\n");
                            mBufferedWriter.flush();
                            LogUtil.d("ah   send msg  == " + json.toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    mActionPositionList.clear();
                }

            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mIsRemoteStart = false;
    }

    class SocketHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String data = (String) msg.obj;
                    LogUtil.e("ah  SocketHandler  data  ========>>   "+data);
                    ActionPosition actionPosition = GsonUtil.gsonToBean(data, ActionPosition.class);
                    mRemoteDrawView.remoteDraw(actionPosition);
                    break;

                default:
                    break;
            }
        }
    }
}
